package bank.service;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bank.model.pool.DBConnectionPool;


public abstract class Dispatcher extends HttpServlet {
	private DBConnectionPool connectionPool;	
	private String forwardURL;
	
	public abstract void performServiceLogic(HttpServletRequest request, HttpServletResponse response) throws Exception;
	
	public void init() {
		this.connectionPool = DBConnectionPool.getInstance();		
	}
	
	public void forward(String address, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(address);
		dispatcher.forward(request, response);		
	}
	
	public void service(HttpServletRequest request, HttpServletResponse response) {
		try {
			this.performServiceLogic(request, response);			
			this.forward(this.getForwardURL(), request, response);		
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("error", e.getMessage());			
			try {
				this.forward("/error.jsp", request, response);
			} catch (Exception e1) {				
				e1.printStackTrace();
			} 
			
		} 
	}
	
	public String getForwardURL() {
		return forwardURL;
	}

	public void setForwardURL(String forwardURL) {
		this.forwardURL = forwardURL;
	}

	public void destroy() {
		this.connectionPool.release();
	}
}
